package com.sprouting.personal.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.sprouting.personal.interfaces.common.Constant;
import com.sprouting.personal.model.common.ResultJson;
import com.sprouting.personal.model.diagram.relationGraph.GraphJsonData;
import com.sprouting.personal.model.diagram.relationGraph.Link;
import com.sprouting.personal.model.diagram.relationGraph.Node;
import com.sprouting.personal.model.entity.Dict;
import com.sprouting.personal.model.entity.Join;
import com.sprouting.personal.model.entity.MemberFamily;
import com.sprouting.personal.model.vo.MemberFamilyTree;
import com.sprouting.personal.service.DictGroupService;
import com.sprouting.personal.service.DictService;
import com.sprouting.personal.service.JoinService;
import com.sprouting.personal.service.MemberFamilyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.Null;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 关系图
 *
 * @author ：LX（长沙麓谷）
 * @date 创建时间： 2022/12/14 14:42
 */
@RequestMapping("/diagram")
@RestController
public class DiagramController {

    @Autowired
    private MemberFamilyService memberFamilyService;
    @Autowired
    private JoinService joinService;
    @Autowired
    private DictService dictService;
    @Autowired
    private DictGroupService dictGroupService;


    /**
     * 获取 relation-Graph 需要的关系图结构
     * @return
     */
    @GetMapping("/getRelationGraph")
    public ResultJson getRelationGraph(){
        String userId = StpUtil.getLoginIdAsString();

        List<MemberFamily> memberFamilyList = memberFamilyService.getDiagramNode(userId);
        List<Join> joinList = joinService.getDiagramLink(userId);

        List<Node<MemberFamily>> nodeList = new ArrayList<>();
        for (MemberFamily memberFamily : memberFamilyList){
            Node<MemberFamily> node = new Node<>();
            node.setId(memberFamily.getId());
            if (Constant.DefaultValue.UNKNOWN_NAME.equals(memberFamily.getUserName())){
                node.setText("名字未知");
                // 下面这个是有图片的那个图才用到
                // memberFamily.setUserName("名字未知");
            } else {
                node.setText(memberFamily.getUserName());
            }

            node.setData(memberFamily);
            nodeList.add(node);
        }


        List<Link<Join>> linkList = new ArrayList<>();
        if (CollUtil.isNotEmpty(joinList)){
            List<String> joinTypeIdList = joinList.stream().map(Join::getConnectionTypeId).distinct().collect(Collectors.toList());
            List<Dict> dictList = dictService.getDictByIdList(joinTypeIdList);
            Map<String, Dict> dictMap = dictList.stream().collect(Collectors.toMap(Dict::getId, Function.identity()));

            for (Join join : joinList){
                Link<Join> link = new Link<>();
                link.setFrom(join.getSourceId());
                link.setTo(join.getTargetId());
                String text = String.format("%s [%s]", join.getDataExplain(), join.getCall());
                link.setText(text);
                link.setData(join);
                String color = getColor(dictMap, join);
                // link.setLineColor(color);
                link.setFontColor(color);

                linkList.add(link);
            }
        }

        GraphJsonData<MemberFamily, Join> graphJsonData = new GraphJsonData<>();
        graphJsonData.setRootId(userId);
        graphJsonData.setNodes(nodeList);
        graphJsonData.setLinks(linkList);

        return ResultJson.success(graphJsonData);
    }

    /**
     * 获取线条颜色
     * @param dictMap 字典映射关系
     * @param join 对应的连接数据
     * @return
     */
    private String getColor(Map<String, Dict> dictMap, Join join){
        if (join == null){
            // 陌生一般关系
            return "#909090";
        }

        Dict dict = dictMap.get(join.getConnectionTypeId());
        if (dict == null){
            // 陌生一般关系
            return "#909090";
        }

        // todo 可优化，也可以做到配置中，但暂时没这一块的需求，先搞完再说。暂时也没配这个颜色
        String code = dict.getCode();
        if (StrUtil.startWith(code, "6") || "1401".equals(code)){
            // 亲戚
            return "#FF0000";
        }
        if ("1402".equals(code)){
            // 朋友
            return "#00FF00";
        }
        if ("1403".equals(code)){
            // 同学-战友
            return "#FF00FF";
        }
        if ("1404".equals(code)){
            // 村民-邻居
            return "#0000FF";
        }
        if ("1405".equals(code)){
            // 同事
            return "#FFFF00";
        }
        if ("1406".equals(code)){
            // 领导
            return "#3399FF";
        }

        return "#909090";
    }

}
